﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.ApproveWorkflow.Interfaces;
using System.Activities;
using Microhard.Core.DBUtility;
using System.Activities.Expressions;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microhard.Core.Algorithm;
using System.Activities.XamlIntegration;
using System.Xaml;
using System.Reflection;
using Microhard.Core;
using Microhard.Core.Core;
using Microhard.Core.Enums;

namespace Microhard.ApproveWorkflow.Impls
{

    //public class WorkflowImpl : Microhard.ApproveWorkflow.Interfaces.IWorkflow
    //{
    //    public bool IsCurrentOperatorInScope(Guid activityID, Guid flowChartID, Guid currentUserID)
    //    {
    //        //判断当前操作人是否在activity操作人范围内
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        var act = db.t_ActivityInWorkFlows.SingleOrDefault(a => a.ActivityID == activityID && a.FlowChartID == flowChartID);
    //        if (act.IsNeedToValidateScope.Value)
    //        {
    //            var scope = db.t_ActivityApproverScopes.Where(a => a.ActivityID == activityID
    //                && a.t_ActivityInWorkFlow.FlowChartID == flowChartID)
    //                .Select(a => a.OwnerID.Value);
    //            return scope.Contains(currentUserID);
    //        }
    //        return true;
    //    }

    //    #region IWorkflow Members
    //    public WorkflowModel GetWorkFlowModel(Guid businessSheetID, Guid resID, out string realResourceKeyName)
    //    {
    //        WorkflowModel rtn = new WorkflowModel();
    //        realResourceKeyName = string.Empty;
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        //业务已经有运行中的工作流
    //        var entity = db.t_WorkflowBusinessSheetRelations.SingleOrDefault(f => f.BusinessSheetID == businessSheetID && f.IsComplete == false);
    //        if (entity != null)
    //        {
    //            realResourceKeyName = entity.t_FlowChart.ResourceKeyName;
    //            rtn = entity.ToModel();
    //            rtn.UserHasAuthToAccessActivity = this.IsCurrentOperatorInScope(entity.CurrentActivityID.Value, entity.FlowChartID.Value, scope.CurrentUserID);
    //        }
    //        else
    //        {
    //            //业务还未发起工作流
    //            var flow = db.t_FlowCharts.SingleOrDefault(t => t.ResourceID == resID && t.OperationID == scope.OperationID);
    //            rtn.BusinessSheetID = businessSheetID;
    //            rtn.ApplierID = scope.CurrentUserID;
    //            rtn.ApplierName = scope.CurrentUserName;
    //            rtn.BusinessSheetResourceName = scope.ResourceName;
    //            rtn.CreationDateTime = DateTime.Now;
    //            rtn.FlowChartID = flow.FlowChartId;
    //            rtn.FlowName = flow.FlowChartName;
    //            rtn.FlowType = flow.t_WorkFlowType.TypeId;
    //            rtn.FlowTypeName = flow.t_WorkFlowType.TypeName;
    //            rtn.HasActivities = flow.t_ActivityInWorkFlows.Select(a => a.ToModel()).ToList();
    //            rtn.LatestModificationDateTime = DateTime.Now;
    //            rtn.OperationKeyName = scope.OperationKeyName.ToLower();
    //            var act = flow.t_ActivityInWorkFlows.Single(a => a.OrderNumber == 1);
    //            rtn.CurrentActivityID = act.ActivityID;
    //            rtn.HasActivities.SingleOrDefault(a => a.OrderNumber == 1).IsCurrent = true;
    //            rtn.UserHasAuthToAccessActivity = this.IsCurrentOperatorInScope(act.ActivityID, flow.FlowChartId, scope.CurrentUserID);
    //        }
    //        return rtn;
    //    }

    //    public Core.DBUtility.ExecutedResult Approve<T>(T model, WorkflowModel wfModel, IRepository<T> busInterface, string busMethodName)
    //    {
    //        ExecutedResult rtn = new ExecutedResult();
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        var chart = this.GetFlowChart(wfModel.BusinessSheetID);
    //        var flow = this.LoadFromXAMLFile(wfModel.WFXAMLFileName);

    //        //装载流程
    //        WorkflowApplication wfApp = new WorkflowApplication(flow);
    //        wfApp.InstanceStore = SqlPersistenceStore.GetStore();
    //        try
    //        {
    //            //装载流程
    //            wfApp.Load(wfModel.WorkflowInstanceID);
    //            //传递审批结果
    //            Dictionary<string, object> parms = new Dictionary<string, object>();
    //            parms.Add("ApproveMessage", string.Empty);
    //            parms.Add("ApproverID", scope.CurrentUserID);
    //            parms.Add("ApproverName", scope.CurrentUserName);
    //            parms.Add("IsRefuse", wfModel.IsRefuse);
    //            parms.Add("FlowchartID", wfModel.FlowChartID);
    //            parms.Add("ActivityID", wfModel.CurrentActivityID);

    //            wfApp.ResumeBookmark(wfModel.CurrentActivity.BookmarkName, parms);
    //            //卸载流程
    //            wfApp.Unload();
    //            //执行业务方法
    //            rtn = WorkFlowUnity.ExecuteRepositoryMethod<T>(model, busInterface, busMethodName);
    //        }
    //        catch (Exception ex)
    //        {
    //            rtn.ErrorMsg.Add("WorkflowImpl.Approve", ex.Message);
    //        }
    //        return rtn;
    //    }

    //    public Core.DBUtility.ExecutedResult Complete(Guid workflowInstanceID, WorkflowModel wfModel)
    //    {
    //        ExecutedResult rtn = new ExecutedResult();
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        //获得业务流程
    //        var chart = db.t_WorkflowBusinessSheetRelations.SingleOrDefault(w => w.WorkflowInstanceID == workflowInstanceID);
    //        var flow = this.LoadFromXAMLFile(wfModel.WFXAMLFileName);

    //        WorkflowApplication wfApp = new WorkflowApplication(flow);
    //        wfApp.InstanceStore = SqlPersistenceStore.GetStore();

    //        try
    //        {
    //            wfApp.Load(workflowInstanceID);
    //            //传递审批结果
    //            //传递审批结果
    //            Dictionary<string, object> parms = new Dictionary<string, object>();
    //            parms.Add("ApproveMessage", string.Empty);
    //            parms.Add("ApproverID", scope.CurrentUserID);
    //            parms.Add("ApproverName", scope.CurrentUserName);
    //            parms.Add("IsRefuse", wfModel.IsRefuse);
    //            parms.Add("FlowchartID", wfModel.FlowChartID);
    //            parms.Add("ActivityID", wfModel.CurrentActivityID);
    //            wfApp.ResumeBookmark(wfModel.CurrentActivity.BookmarkName, parms);
    //            //卸载流程
    //            wfApp.Unload();
    //        }
    //        catch (Exception ex)
    //        {
    //            rtn.ErrorMsg.Add("WorkflowImpl.Complete", ex.Message);
    //        }
    //        return rtn;
    //    }

    //    #endregion

    //    #region IRepository<WorkflowModel> Members

    //    public Core.DBUtility.ExecutedResult Add(Models.WorkflowModel model)
    //    {
    //        throw new NotImplementedException();
    //    }

    //    public Core.DBUtility.ExecutedResult Update(Models.WorkflowModel model)
    //    {
    //        throw new NotImplementedException();
    //    }

    //    public Core.DBUtility.ExecutedResult Delete(List<Guid> ids)
    //    {
    //        throw new NotImplementedException();
    //    }

    //    public Core.DBUtility.ExecutedResult Delete(Models.WorkflowModel model)
    //    {
    //        throw new NotImplementedException();
    //    }

    //    public Models.WorkflowModel GetModelByID(Guid id)
    //    {
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        var entity = db.t_WorkflowBusinessSheetRelations.SingleOrDefault(b => b.WBSRID == id);
    //        if (entity != null)
    //            return entity.ToModel();
    //        return null;
    //    }

    //    public Models.WorkflowModel GetModelByModel(Models.WorkflowModel model)
    //    {
    //        throw new NotImplementedException();
    //    }

    //    /// <summary>
    //    /// 获得和我相关的流程
    //    /// </summary>
    //    /// <param name="Model"></param>
    //    /// <param name="pageIndex"></param>
    //    /// <param name="pageSize"></param>
    //    /// <param name="totalCount"></param>
    //    /// <returns></returns>
    //    public List<Models.WorkflowModel> Query(Models.WorkflowModel Model, int pageIndex, int pageSize, out int totalCount)
    //    {
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        IEnumerable<t_WorkflowBusinessSheetRelation> entities = null;
    //        entities = from b in db.t_WorkflowBusinessSheetRelations
    //                   from u in b.t_ActivityInWorkFlow.t_ActivityApproverScopes
    //                   where u.OwnerID == scope.CurrentUserID && u.OwnerType == (int)OwnerIDType.User
    //                   select b;
    //        totalCount = entities.Count();
    //        var pagedEntities = entities.OrderByDescending(p => p.CreationDateTime).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
    //        return pagedEntities.Select(p => p.ToModel()).ToList();
    //    }

    //    public List<Models.WorkflowModel> Query(Models.WorkflowModel Model)
    //    {
    //        throw new NotImplementedException();
    //    }

    //    public Core.DBUtility.ScopeResult scope
    //    {
    //        set;
    //        get;
    //    }

    //    #endregion




    //    #region IWorkflow Members

    //    public ApproveFlowChat GetFlowChart(Guid resourceID, Guid operationID)
    //    {
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        var flowChart = db.t_FlowCharts.SingleOrDefault(s => s.ResourceID == resourceID && s.OperationID == operationID);
    //        if (flowChart != null)
    //            return flowChart.ToModel();
    //        return null;
    //    }

    //    public ApproveFlowChat GetFlowChart(Guid businessID)
    //    {
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        var flowChart = db.t_WorkflowBusinessSheetRelations.SingleOrDefault(s => s.BusinessSheetID == businessID);
    //        if (flowChart != null)
    //            return flowChart.t_FlowChart.ToModel();
    //        return null;
    //    }

    //    public bool HasFlow(Guid businessID)
    //    {
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        return db.t_WorkflowBusinessSheetRelations.Count(f => f.BusinessSheetID == businessID && f.IsComplete == true) > 0 ? true : false;
    //    }


    //    private void LogBuzModel(object model, Guid busID, Guid flowChartID, Guid activityID, Guid workFlowInstanceID)
    //    {
    //        ExecutedResult rtn = new ExecutedResult();
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        var theResult = db.t_ApproveResultInActivities.SingleOrDefault(w => w.ActivityID == activityID &&
    //            w.FlowChartID.Value == flowChartID
    //            && w.WorkFlowInstanceID.Value == workFlowInstanceID
    //            && scope.CurrentUserID == w.OperatorID);
    //        Type type = model.GetType();

    //        if (theResult == null)
    //        {
    //            //记录各个审批点，对业务数据的修改
    //            var toAdd = new t_ApproveResultInActivity();
    //            toAdd.ApproveResultID = Guid.NewGuid();
    //            toAdd.Model = AlgCompare.SeriesDataToByte(model);
    //            toAdd.ClassName = type.Name;
    //            toAdd.NameSpace = type.Namespace;
    //            toAdd.CreationTime = DateTime.Now;
    //            toAdd.ModificationTime = DateTime.Now;
    //            toAdd.OperatorID = scope.CurrentUserID;
    //            toAdd.OperatorName = scope.CurrentUserName;
    //            toAdd.ActivityID = activityID;
    //            toAdd.FlowChartID = flowChartID;
    //            toAdd.WorkFlowInstanceID = workFlowInstanceID;
    //            toAdd.ApproveMessage = scope.OperationKeyName;

    //            db.t_ApproveResultInActivities.InsertOnSubmit(toAdd);
    //        }
    //        else
    //        {
    //            theResult.Model = AlgCompare.SeriesDataToByte(model);
    //            theResult.ModificationTime = DateTime.Now;
    //            theResult.ClassName = type.Name;
    //            theResult.NameSpace = type.Namespace;
    //        }

    //        db.SubmitChanges();

    //    }


    //    public object GetApprovedBuzModel(Guid workflowInstanceID)
    //    {
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        var acts = (from f in db.t_WorkflowBusinessSheetRelations
    //                    from a in db.t_ActivityInWorkFlows
    //                    where f.WorkflowInstanceID == workflowInstanceID
    //                    select a).OrderByDescending(p => p.OrderNumber).ToList();
    //        int apPoint = acts.Count - 2;
    //        var theAct = acts[apPoint];
    //        var data = db.t_ApproveResultInActivities.SingleOrDefault(b => b.WorkFlowInstanceID == workflowInstanceID
    //            && b.FlowChartID == acts.First().FlowChartID
    //            && b.ActivityID == theAct.ActivityID);
    //        byte[] modelBytes = data.Model.ToArray();
    //        return AlgCompare.DeseriesBytesToObject(modelBytes);
    //    }

    //    private DynamicActivity LoadFromXAMLFile(string fileName)
    //    {
    //        return FlowHelper.LoadActivityFromFile(fileName);
    //    }


    //    #endregion



    //    #region IWorkflow Members


    //    public ExecutedResult Apply<T>(T model, WorkflowModel wfModel, IRepository<T> busInterface)
    //    {
    //        ExecutedResult rtn = new ExecutedResult();
    //        //根据flowKeyName 获得流程图
    //        DynamicActivity flow = this.LoadFromXAMLFile(wfModel.WFXAMLFileName);
    //        //构造流程的InArgument
    //        var busID = AlgCompare.GetPKID<ModelPKIDAttribute>(model);
    //        IDictionary<string, object> parms = new Dictionary<string, object>();
    //        parms.Add("BusinessSheetID", busID);
    //        parms.Add("OperatorID", scope.CurrentUserID);
    //        parms.Add("OperatorName", scope.CurrentUserName);
    //        //流程开始，传入申请人的相关信息 
    //        WorkflowApplication wfApp = new WorkflowApplication(flow, parms);
    //        wfApp.InstanceStore = SqlPersistenceStore.GetStore();
    //        //指定为unload,代表需要固化workflow并从内存中unload
    //        //指定为persist,会被workflow的实例锁定，退出并不是以unload方式,通常再次获取、
    //        //实例的时候，会出现错误“此流程被一个实例锁定，无法提取”
    //        wfApp.PersistableIdle = (e) =>
    //        {
    //            return PersistableIdleAction.Unload;
    //        };


    //        try
    //        {
    //            //启动流程
    //            wfApp.Run();

    //            //保存业务数据
    //            if (busInterface != null)
    //            {
    //                rtn = busInterface.Add(model);
    //            }
    //            rtn.WorkflowInstanceID = wfApp.Id;
    //            rtn.ExecutedModel = model;
    //        }
    //        catch (Exception ex)
    //        {
    //            rtn.ErrorMsg.Add("WorkflowImpl.Add", ex.Message);
    //        }
    //        return rtn;
    //    }

    //    public ExecutedResult ReApply(object model, Guid workflowInstanceID, WorkflowModel wfModel)
    //    {
    //        ExecutedResult rtn = new ExecutedResult();
    //        WorkflowDBDataContext db = new WorkflowDBDataContext();
    //        var chart = db.t_WorkflowBusinessSheetRelations.SingleOrDefault(w => w.WorkflowInstanceID == workflowInstanceID);

    //        var flow = this.LoadFromXAMLFile(wfModel.WFXAMLFileName);
    //        //装载流程
    //        WorkflowApplication wfApp = new WorkflowApplication(flow);
    //        wfApp.InstanceStore = SqlPersistenceStore.GetStore();
    //        try
    //        {
    //            wfApp.Load(workflowInstanceID);
    //            //卸载流程
    //            wfApp.Unload();
    //            //保存业务数据
    //            this.LogBuzModel(model, chart.BusinessSheetID, wfModel.FlowChartID, wfModel.CurrentActivityID, wfApp.Id);
    //        }
    //        catch (Exception ex)
    //        {
    //            rtn.ErrorMsg.Add("WorkflowImpl.ReApply", ex.Message);
    //        }
    //        return rtn;
    //    }
    //    #endregion
    //}
}
